﻿using System;
using System.Collections.Generic;
using System.Text;
using MSNPSharp;
using MSNPSharp.Core;
using System.Diagnostics;
using System.Threading;

namespace MSNControlPlugin
{
    public class Plugin : Plugins.IPlugin
    {
        System.Threading.Timer chatterBotTimer;        
        public Plugin()
        {
            //string cb = System.Configuration.ConfigurationSettings.AppSettings["ChatterBot"];
            //bool.TryParse(cb, out chatterBotEnabled);            
            //if (ChatterBotEnabled) EnableChatterBot();
        }
        System.Random rnd = new Random();
        int ChatterBotFrequency = 3600000;
        private MSNPSharp.Contact ChatterContact = null;
        private void Chatter(object state)
        {
            if (ChatterContact == null && Messenger != null && ChatterBotEnabled)
            {
                int citem = rnd.Next(Messenger.ContactList.Count - 1);
                MSNPSharp.Contact rndContact = null;
                int index = 0;
                foreach (MSNPSharp.Contact contact in Messenger.ContactList.Values)
                {
                    rndContact = contact;
                    if (index >= citem && rndContact.Online && rndContact.Mail != Messenger.Owner.Mail) break;
                    index++;
                }
                if (rndContact != null)
                {
                    ChatterContact = rndContact;
                    Messenger.CreateConversation();
                }
            }
            if (Messenger == null && ChatterBotEnabled && ChatterContact != null) ChatterContact = null;
        }

        void Messenger_ConversationCreated(object sender, ConversationCreatedEventArgs e)
        {
            if (ChatterContact != null)
            {
                Trace.WriteLine("Starting a random conversation with:" + ChatterContact.Mail);
                e.Conversation.Switchboard.ContactJoined += new EventHandler<ContactEventArgs>(Switchboard_ContactJoined);
                e.Conversation.Invite(ChatterContact);
            }
        }
        List<string> Openers = new List<string>() { "Hello there", "How are you?", "Whats new?", "Want to chat?", "What are you up to?" };
        void Switchboard_ContactJoined(object sender, ContactEventArgs e)
        {
            if (e.Contact != null && e.Contact.Mail == ChatterContact.Mail)
            {                
                MSNPSharp.SBMessageHandler handler = (sender as MSNPSharp.SBMessageHandler);
                if (handler != null)
                {
                    Trace.WriteLine("Sending random message");
                    handler.SendTextMessage(new TextMessage(Openers[rnd.Next(Openers.Count-1)]));
                }
                ChatterContact = null;
            }
            
        }
        private void EnableChatterBot()
        {
            ChatterBotEnabled = true;
            if (chatterBotTimer == null)
                chatterBotTimer = new System.Threading.Timer(new System.Threading.TimerCallback(Chatter), null, 10000, ChatterBotFrequency);
            else
                chatterBotTimer.Change(ChatterBotFrequency, ChatterBotFrequency);

            System.Diagnostics.Trace.WriteLine("Chatterbot Enabled");
        }
        private void DisableChatterBot()
        {
            ChatterBotEnabled = false;
            chatterBotTimer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
            System.Diagnostics.Trace.WriteLine("Chatterbot Disabled");
        }

        #region IPlugin Members
        public string Name { get { return "MSN Controller"; } }
        public List<string> Command
        {
            get { return new List<string>() { "msn", "startchatterbot", "stopchatterbot" }; }
        }

        public string RootStore { get; set; }

        public MSNPSharp.Messenger Messenger { get; set; }

        private bool chatterBotEnabled = false;
        public bool ChatterBotEnabled
        {
            get
            {
                return chatterBotEnabled;
            }
            set
            {
                chatterBotEnabled = value;
            }
        }
        private bool HasConvEvent = false;
        public string Chat(string Command, string UserID, string Input)
        {
            string owner = System.Configuration.ConfigurationSettings.AppSettings["Owner"];
            if (Messenger != null && !HasConvEvent)
            {
                HasConvEvent = true;
                Messenger.ConversationCreated += new EventHandler<ConversationCreatedEventArgs>(Messenger_ConversationCreated);
            }
            if (UserID == owner)
            {
                if (Command == "msn")
                {
                    string lower = Input.ToLower().Trim();

                    if (lower.StartsWith("/?"))
                    {
                        return "msn command help:\nUseage:\nChange the Bot's Display Name: msn displayname NEWNAME\nChange the Personal Message: msn personal MSG\nChange the display picture: msn displaypicture URL\n\nThis plugin also allows for starting and stopping the chatter bot:  startchatterbot or stopchatterbot" ;
                    }
                    if (lower.StartsWith("displayname"))
                    {
                        string dn = Input.Trim().Substring("displayname".Length).Trim();
                        //Messenger.Nameserver.SetScreenName(dn);
                        return "Display name set:" + dn;
                    }
                    else if (lower.StartsWith("personal"))
                    {
                        string dn = Input.Trim().Substring("personal".Length);
                        //Messenger.Nameserver.SetPersonalMessage((new MSNPSharp.PersonalMessage(dn, MSNPSharp.MediaType.None, null, Guid.NewGuid())));
                        return "Personal Message Set:" + dn;
                    }
                    else if (lower.StartsWith("displaypicture"))
                    {
                        string path = Input.Trim().Substring("displaypicture".Length);
                        string finalPath = SetDisplayPicture(path);
                        return "New Display Picture Set:" + finalPath;
                    }
                }
                else if (Command == "startchatterbot")
                {
                    EnableChatterBot();
                    return "Chatter Bot Started";
                }
                else if (Command == "stopchatterbot")
                {
                    DisableChatterBot();
                    return "Chatter Bot Stopped";
                }
            }
            return "";
        }
        public string SetDisplayPicture(string Path)
        {
            string origUrl = "";
            try
            {
                string pth = System.IO.Path.Combine(RootStore, @"DisplayImages");
                if (!System.IO.Directory.Exists(pth)) System.IO.Directory.CreateDirectory(pth);

                if (Path.ToUpper().IndexOf("HTTP") >= 0)
                {
                    origUrl = Path;
                    try
                    {
                        string filename = System.IO.Path.Combine(pth, System.Guid.NewGuid().ToString());

                        System.Net.WebClient wc = new System.Net.WebClient();
                        wc.DownloadFile(Path, filename);
                        Path = filename;
                    }
                    catch (Exception)
                    {
                        Path = "";
                    }
                }
                if (!System.IO.File.Exists(Path))
                {
                    Path = pth + Path;
                    if (!System.IO.File.Exists(Path)) Path = "";
                }

                if (Path != "")
                {
                    bool resize = false;
                    int w = 0;
                    int h = 0;
                    string tempFile = Path + "TEMP";
                    System.Drawing.Bitmap b = new System.Drawing.Bitmap(Path);
                    if (b.RawFormat != System.Drawing.Imaging.ImageFormat.Png)
                    {
                        b.Save(tempFile, System.Drawing.Imaging.ImageFormat.Png);
                    }
                    if (b.Width > 100 || b.Height > 100)
                    {
                        w = b.Width;
                        h = b.Height;
                        resize = true;
                    }
                    b.Dispose();

                    System.IO.File.Move(tempFile, Path + ".png");
                    Path = Path + ".png";

                    if (resize)
                    {
                        if (w - 100 > h - 100)
                        {
                            //scale based on a max width of 100
                            double factor = w / 100;
                            w = 100;
                            h = (int)((double)h / factor);
                        }
                        else
                        {
                            //scale based on a max hight of 100
                            double factor = h / 100;
                            h = 100;
                            w = (int)((double)w / factor);
                        }
                        b = new System.Drawing.Bitmap(Path);
                        System.Drawing.Image small = b.GetThumbnailImage(w, h, null, System.IntPtr.Zero);
                        b.Dispose();
                        small.Save(Path);

                    }
                    b = new System.Drawing.Bitmap(Path);

                    DisplayImage image = new DisplayImage(Messenger.Owner.Mail);
                    image.Image = b;
                    Messenger.Owner.DisplayImage = image;
                    //pngImage.Dispose();
                }
                //DisplayImagePath = Path;
                //if (origUrl != "") DisplayImagePath = origUrl;
                return Path;
            }
            catch (Exception exc)
            {
                return exc.ToString();
            }
        }
        #endregion
    }
}
